import { wallet } from '@/models/wallet'

async function eachAccount (accountsObject, net) {
  wallet.setNet(net)
  for (const [name, account] of Object.entries(accountsObject)) {
    // only bytom1 account, need to create bytom2 account
    if (account.address.startsWith('bm') || account.address.startsWith('tm')) {
      account.bytom1 = {
        address: account.address,
        guid: account.guid
      }
      wallet.setChain('bytom')
      const bytom2Account = await wallet.createAccount(account.xpub, account.guid)
      account.address = bytom2Account.address
    }
    // only bytom2 account, need to create bytom1 account
    if ((account.address.startsWith('bn') || account.address.startsWith('tn')) && !account.bytom1) {
      wallet.setChain('bytom1')
      const bytom1Account = await wallet.createAccount(account.xpub, account.guid)
      account.bytom1 = {
        address: bytom1Account.address,
        guid: bytom1Account.guid
      }
    }
  }
}

export const m3_3_0 = async bytom => {
  console.log('begin update config');

  if (bytom.keychain.pairs && bytom.keychain.pairs.mainnet) {
    await eachAccount(bytom.keychain.pairs.mainnet, 'mainnet')
  } else {
    bytom.keychain.pairs.mainnet = {}
  }

  if (bytom.keychain.pairs && bytom.keychain.pairs.testnet) {
    await eachAccount(bytom.keychain.pairs.testnet, 'testnet')
  } else {
    bytom.keychain.pairs.testnet = {}
  }

  if (bytom.settings.netType === 'vapor') {
    wallet.setChain('vapor')
  } else if (bytom.settings.chainType === 'bytom1') {
    wallet.setChain('bytom1')
  } else {
    wallet.setChain('bytom')
  }

  if (bytom.settings.network === 'testnet') {
    const alias = Object.keys(bytom.keychain.pairs.testnet)[0]
    bytom.currentAccount = bytom.keychain.pairs.testnet[alias]
  } else {
    const alias = Object.keys(bytom.keychain.pairs.mainnet)[0]
    bytom.currentAccount = bytom.keychain.pairs.mainnet[alias]
  }
  wallet.setNet(bytom.settings.network)

  console.log('update config success');

  return true;
};
